package com.abraxascorp.managers;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import javax.jdo.Transaction;

import com.abraxascorp.utils.PMF;

/**
 * Class for managing JDO objects
 * 
 * @author devin.partlow
 */
public class JDOManager<E> {
	private final PersistenceManagerFactory pmf;
	
	public JDOManager() {
		pmf = PMF.getPersistenceManagerFactory();
	}
	
    /**
     * Persist an object into the db
     * 
     * @param object Object to persist
     * @return true if successful
     */
    public boolean persist(E object) {
    	if(object == null)
    		return false;
    	
    	PersistenceManager pm = pmf.getPersistenceManager();
    	Transaction tx = pm.currentTransaction();
        boolean didPersist = false;

        try {
        	tx.begin();
        	pm.makePersistent(object);
            didPersist = true;
            tx.commit();
        } finally {
        	if (tx.isActive()) {
                tx.rollback();
            }
        	pm.close();
        }

        return didPersist;
    }
    
    /**
     * Find all objects with matching fields
     * 
     * @param object Object with field to match
     * @param field Field to match
     * @return List of objects with matching fields
     */
	@SuppressWarnings("unchecked")
	public List<E> findObjectsWithField(String fieldName, Object fieldValue, Class<E> clazz) {
		List<E> objectList = new ArrayList<E>();
		
		if(fieldName == null || fieldValue == null)
			return objectList;
		
		PersistenceManager pm = pmf.getPersistenceManager();        
        Query query = null;
    	try{
    		query = pm.newQuery(clazz);
    		query.setFilter(fieldName +" == "+ fieldName +"Param");
            query.declareParameters(fieldValue.getClass().getCanonicalName() +" "+ fieldName +"Param");
            objectList.addAll((List<E>)query.execute(fieldValue));
    	} catch (Exception e) {
    		// keep it moving
    	} finally {
    		if(query != null)
    			query.closeAll();
    		pm.close();
    	}

        return objectList;
	}
}
